package com.example.bgdharaniPlayer.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.bgdharaniPlayer.model.AudioTrack;
import com.example.bgdharaniPlayer.model.Playlist;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 播放列表存储工具类，用于保存和加载播放列表
 */
public class PlaylistStorage {
    private static final String TAG = "PlaylistStorage";
    private static final String PREF_NAME = "playlist_prefs";
    private static final String KEY_PLAYLISTS = "playlists_data";
    private static final String KEY_CURRENT_PLAYLIST = "current_playlist_id";

    /**
     * 保存播放列表到 SharedPreferences
     */
    public static void savePlaylist(Context context, Playlist playlist) {
        if (context == null || playlist == null) {
            return;
        }

        try {
            // 先加载所有播放列表
            Map<String, Playlist> playlists = loadAllPlaylists(context);
            
            // 更新或添加当前播放列表
            playlists.put(playlist.getId(), playlist);
            
            // 保存所有播放列表
            saveAllPlaylists(context, playlists);
            
            Log.d(TAG, "播放列表已保存，ID: " + playlist.getId() + "，名称: " + playlist.getName() + "，共 " + playlist.size() + " 个音频");
        } catch (Exception e) {
            Log.e(TAG, "保存播放列表失败: " + e.getMessage());
        }
    }

    /**
     * 保存所有播放列表到 SharedPreferences
     */
    private static void saveAllPlaylists(Context context, Map<String, Playlist> playlists) {
        if (context == null || playlists == null) {
            return;
        }

        try {
            SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();

            JSONArray playlistsArray = new JSONArray();
            for (Playlist playlist : playlists.values()) {
                JSONObject playlistJson = new JSONObject();
                playlistJson.put("id", playlist.getId());
                playlistJson.put("name", playlist.getName());
                playlistJson.put("order", playlist.getOrder());

                JSONArray tracksArray = new JSONArray();
                for (AudioTrack track : playlist.getTracks()) {
                    JSONObject trackJson = new JSONObject();
                    trackJson.put("id", track.getId());
                    trackJson.put("path", track.getPath());
                    trackJson.put("title", track.getTitle());
                    trackJson.put("playbackSpeed", track.getPlaybackSpeed());
                    trackJson.put("repeatCount", track.getRepeatCount());
                    trackJson.put("isPlaying", track.isPlaying());
                    tracksArray.put(trackJson);
                }

                playlistJson.put("tracks", tracksArray);
                playlistsArray.put(playlistJson);
            }

            editor.putString(KEY_PLAYLISTS, playlistsArray.toString());
            editor.apply();

            Log.d(TAG, "所有播放列表已保存，共 " + playlists.size() + " 个播放列表");
        } catch (JSONException e) {
            Log.e(TAG, "保存所有播放列表失败: " + e.getMessage());
        }
    }

    /**
     * 从 SharedPreferences 加载所有播放列表
     */
    public static Map<String, Playlist> loadAllPlaylists(Context context) {
        Map<String, Playlist> playlists = new HashMap<>();
        
        if (context == null) {
            return playlists;
        }

        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String playlistsJson = prefs.getString(KEY_PLAYLISTS, null);

        if (playlistsJson == null) {
            // 如果没有保存的播放列表，创建一个默认播放列表
            Playlist defaultPlaylist = new Playlist("默认播放列表");
            playlists.put(defaultPlaylist.getId(), defaultPlaylist);
            return playlists;
        }

        try {
            JSONArray playlistsArray = new JSONArray(playlistsJson);
            for (int i = 0; i < playlistsArray.length(); i++) {
                JSONObject playlistJson = playlistsArray.getJSONObject(i);
                
                String id = playlistJson.getString("id");
                String name = playlistJson.getString("name");
                Playlist playlist = new Playlist(id, name);
                
                // 读取order属性，如果不存在则使用默认值0
                if (playlistJson.has("order")) {
                    playlist.setOrder(playlistJson.getInt("order"));
                }

                JSONArray tracksArray = playlistJson.getJSONArray("tracks");
                for (int j = 0; j < tracksArray.length(); j++) {
                    JSONObject trackJson = tracksArray.getJSONObject(j);
                    
                    String path = trackJson.getString("path");
                    String title = trackJson.getString("title");
                    AudioTrack track = new AudioTrack(path, title);
                    
                    track.setPlaybackSpeed((float) trackJson.getDouble("playbackSpeed"));
                    track.setRepeatCount(trackJson.getInt("repeatCount"));
                    track.setPlaying(trackJson.getBoolean("isPlaying"));
                    
                    playlist.addTrack(track);
                }
                
                playlists.put(playlist.getId(), playlist);
            }

            Log.d(TAG, "所有播放列表已加载，共 " + playlists.size() + " 个播放列表");
            return playlists;
        } catch (JSONException e) {
            Log.e(TAG, "加载所有播放列表失败: " + e.getMessage());
            
            // 如果加载失败，创建一个默认播放列表
            Playlist defaultPlaylist = new Playlist("默认播放列表");
            playlists.put(defaultPlaylist.getId(), defaultPlaylist);
            return playlists;
        }
    }

    /**
     * 从 SharedPreferences 加载指定 ID 的播放列表
     */
    public static Playlist loadPlaylist(Context context, String playlistId) {
        Map<String, Playlist> playlists = loadAllPlaylists(context);
        
        if (playlists.containsKey(playlistId)) {
            return playlists.get(playlistId);
        } else {
            // 如果找不到指定 ID 的播放列表，返回第一个播放列表
            if (!playlists.isEmpty()) {
                return playlists.values().iterator().next();
            } else {
                // 如果没有任何播放列表，创建一个默认播放列表
                return new Playlist("默认播放列表");
            }
        }
    }
    
    /**
     * 从 SharedPreferences 加载默认播放列表（向后兼容）
     */
    public static Playlist loadPlaylist(Context context) {
        // 获取当前选中的播放列表 ID
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String currentPlaylistId = prefs.getString(KEY_CURRENT_PLAYLIST, null);
        
        if (currentPlaylistId != null) {
            // 如果有保存当前播放列表 ID，加载该播放列表
            return loadPlaylist(context, currentPlaylistId);
        } else {
            // 否则加载第一个播放列表
            Map<String, Playlist> playlists = loadAllPlaylists(context);
            if (!playlists.isEmpty()) {
                return playlists.values().iterator().next();
            } else {
                return new Playlist("默认播放列表");
            }
        }
    }
    
    /**
     * 删除指定 ID 的播放列表
     */
    public static void deletePlaylist(Context context, String playlistId) {
        if (context == null || playlistId == null) {
            return;
        }
        
        try {
            // 先加载所有播放列表
            Map<String, Playlist> playlists = loadAllPlaylists(context);
            
            // 删除指定 ID 的播放列表
            if (playlists.containsKey(playlistId)) {
                playlists.remove(playlistId);
                Log.d(TAG, "播放列表已删除，ID: " + playlistId);
                
                // 保存所有播放列表
                saveAllPlaylists(context, playlists);
                
                // 如果删除的是当前选中的播放列表，重置当前选中的播放列表
                SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
                String currentPlaylistId = prefs.getString(KEY_CURRENT_PLAYLIST, null);
                if (playlistId.equals(currentPlaylistId)) {
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.remove(KEY_CURRENT_PLAYLIST);
                    editor.apply();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "删除播放列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 保存当前选中的播放列表 ID
     */
    public static void saveCurrentPlaylistId(Context context, String playlistId) {
        if (context == null || playlistId == null) {
            return;
        }
        
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_CURRENT_PLAYLIST, playlistId);
        editor.apply();
        
        Log.d(TAG, "当前播放列表 ID 已保存: " + playlistId);
    }
    
    /**
     * 获取当前选中的播放列表 ID
     */
    public static String getCurrentPlaylistId(Context context) {
        if (context == null) {
            return null;
        }
        
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_CURRENT_PLAYLIST, null);
    }
}
